package com.example.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.domain.BackMessage;
import com.example.domain.Message;
import com.example.domain.ResultData;
import com.example.domain.User;
import com.example.mapper.MessageMapper;
import com.example.mapper.UserMapper;
import com.example.service.BackMessageType;
import com.example.service.FriendService;
import com.example.service.MessageService;
import com.example.service.MessageType;
import com.example.util.IDUtil;
import com.example.vo.MessageVo;
import com.example.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.websocket.Session;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author zhouxl
 * @DATE 2021/2/2
 * @descriptoin
 */
@Component("messageService")
@Transactional
public class MessageServiceImpl implements MessageService {

    @Autowired
    private FriendService friendService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public BackMessage getMessage(String message, Session session) {
        Message msg = JSONObject.parseObject(message, Message.class);
        if (MessageType.MSG_TYPE_ADD_FRIEND.equals(msg.getMsgType())) { // 添加好友信息
            return friendService.addFriend(msg, session);
        } else if (MessageType.MSG_TYPE_REJECT_FRIEND.equals(msg.getMsgType())) { // 拒接添加好友请求
            return friendService.rejectFriend(msg, session);
        } else if (MessageType.MSG_TYPE_AGREE_FRIEND.equals(msg.getMsgType())) {  // 同意添加好友
            return friendService.agreeFriend(msg, session);
        } else if (MessageType.MSG_TYPE_TEXT.equals(msg.getMsgType())) {  // 处理文本消息
            return dealTextMessage(msg, session);
        }
        return new BackMessage();
    }

    /**
     * 处理文本消息
     *
     * @param msg
     * @param session
     * @return
     */
    public BackMessage dealTextMessage(Message msg, Session session) {
        /*
        处理逻辑
        1.判断当前发送消息的用户是否在线
        2.如果在线，直接发送消息给用户，并存入当前消息到数据库，并把消息设置为已读
        3.如果当前用户不在线，设置消息为未读，不发送消息给客户端
         */
        BackMessage backMessage = new BackMessage();
        String toUser = msg.getToUser();
        boolean login = WebSocketServer.isLogin(toUser);
        msg.setReadType(login ? MessageType.MSG_READ_TYPE_YES : MessageType.MSG_READ_TYPE_NO);
        msg.setMid(IDUtil.UUID());
        msg.setMsgDate(new Date());
        // 将消息信息存入数据库
        messageMapper.addMessage(msg);

        // 返回统一的消息类型
        BeanUtils.copyProperties(msg, backMessage);
        backMessage.setSendFlag(login ? BackMessageType.SEND_FLAG_YES : BackMessageType.SEND_FLAG_NO);
        backMessage.setDialog(BackMessageType.DIALOG_NO);
        backMessage.setMsgFlag(BackMessageType.MSG_FLAG_SUCCESS);

        return backMessage;
    }

    /***
     * 欢迎回来
     * @param uid
     * @param session
     * @return
     */
    public BackMessage welcomeBack(String uid, Session session) {
        BackMessage msg = new BackMessage();
        msg.setMsgType(BackMessageType.MSG_TYPE_SYSTEM);
        msg.setFromUser(uid);
        msg.setContent("欢迎回来");
        User user = userMapper.findByUid(uid);
        if (Objects.isNull(user)) {
            msg.setMsgFlag(BackMessageType.MSG_FLAG_ERROR);
            msg.setContent("用户信息丢失了");
        } else {
            msg.setFromUserName(user.getName());
            msg.setToUser(uid);
            msg.setToUserName(user.getName());
        }
        return msg;
    }

    @Override
    public ResultData queryNoReadMessage(MessageVo messageVo) {
        ResultData data = ResultData.success(null);
        messageVo.setMsgType(MessageType.MSG_TYPE_TEXT);
//        // 获取未读的消息信息
//        List<Map<String,Object>> messages = messageMapper.updateNoReadMessage(messageVo);
//        // 将消息设置为已读
        messageVo.setReadType(MessageType.MSG_READ_TYPE_YES);
        int update = messageMapper.readedMessage(messageVo);
        data.setData(update);
        return data;
    }

    @Override
    public List<BackMessage> broadcaseLoginMessage(String uid, Session session) {
        return friendService.broadcaseLoginMessage(uid, session);
    }


}
